//
//  XBshoppingController.m
//  xunbao
//
//  Created by 程顺晓 on 16/4/4.
//  Copyright © 2016年 itcast. All rights reserved.
//


#import "UIView+SDAutoLayout.h"
#import "XBshoppingController.h"
#import "XBShopping.h"
#import "XBShoppingCell.h"
#import "XBList.h"
#import "SDRefresh.h"
#import "XBTagListView.h"
#define cnt 2

@interface XBshoppingController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;

@property (nonatomic, weak) UIView *tagListView;
@property (nonatomic, strong) UIButton *updownbtn;

@property (nonatomic, strong) UIView *addView;

//shopping模型数组
@property (nonatomic, strong) NSMutableArray *shoppings;
//listURL数组
@property (nonatomic, strong) NSMutableArray *listURLs;
@property (nonatomic, assign) int index;

@property (nonatomic, strong) XBTagListView *xbtagListView;

@property (nonatomic, copy) NSString *idString;
@end

@implementation XBshoppingController{
    SDRefreshFooterView *_refreshFooter;
    SDRefreshHeaderView *_refreshHeader;
}

static NSString * const reuseIdentifier = @"shopCell";
- (BOOL)prefersStatusBarHidden{
    return YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectionView.dataSource = self;
//    self.layout.sectionInset = UIEdgeInsetsMake(0, 0, 49, 0);
//    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, -49, 0);
    
    
    //去除导航栏分割线
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    //去除分割线
    [self.navigationController.navigationBar setTranslucent:NO];
    //跟随界面的滚动而往上隐藏
    self.navigationController.hidesBarsOnSwipe = YES;
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    
    
    //初始化url数组
    self.listURLs = [self setupUrlArray];
    
    
    //上拉、下拉刷新
    [self upDownReloadData];
    
    [self setupTigLabel];
    [self layoutCollectionView];

    XBTagListView *tagListView = [[XBTagListView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
    tagListView.backgroundColor = [UIColor whiteColor];
    tagListView.clipsToBounds = YES;
    self.xbtagListView = tagListView;
    [self.view addSubview:tagListView];
   
    //刷新数据
    [self reloadData];
}

/**
 *  初始化url数组
 */
- (NSMutableArray *)setupUrlArray{
    NSMutableArray *arrayM = [NSMutableArray array];
    
    for (int i = 0; i < 100; ++i) {
        __weak NSString *url ;
        if (self.idString == nil) {
            
            url =[NSString stringWithFormat:@"http://api.xunbaozl.com/v2/post/loadAuction?page=%d&size=8&postType=2&tagId=all",i];
        }else {
             url =[NSString stringWithFormat:@"http://api.xunbaozl.com/v2/post/loadAuction?page=%d&size=8&postType=2&tagId=%@",i,self.idString];
        }
        
        [arrayM addObject:url];
    }
    return arrayM;
}
/**
 *  上拉、下拉刷新
 */
- (void)upDownReloadData{
    __weak typeof(self) weakSelf = self;
    // 上拉加载
    _refreshFooter = [SDRefreshFooterView refreshView];
    [_refreshFooter addToScrollView:self.collectionView];
    __weak typeof(_refreshFooter) weakRefreshFooter = _refreshFooter;

    _refreshFooter.beginRefreshingOperation = ^() {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf reloadData];
//            NSLog(@"%zd",weakSelf.shoppings.count);
//            NSLog(@"---%@",weakSelf.listURLs[self.index]);

//            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:(weakSelf.shoppings.count - 1) inSection:0];
//            [weakSelf.collectionView scrollToItemAtIndexPath:xx atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
            [weakRefreshFooter endRefreshing];
        });
    };
    // 下拉加载
    _refreshHeader = [SDRefreshHeaderView refreshView];
    [_refreshHeader addToScrollView:self.collectionView];
    __weak typeof(_refreshHeader) weakRefreshHeader = _refreshHeader;
    _refreshHeader.beginRefreshingOperation = ^() {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf reloadData];

            [weakRefreshHeader endRefreshing];
        });
    };
}

/**
 *  刷新数据
 */
- (void)reloadData{
    //设置点击后获取id  根据id来拼接一个url,然后属性数据
    [self.xbtagListView setTagListBlock:^(NSString *idString) {
        self.idString = idString;
//        NSLog(@"---%@",self.idString);
//        NSLog(@"%@",self.listURLs[self.index]);
        
        self.listURLs = [self setupUrlArray];
        
        self.shoppings = nil;
        [XBShopping loadNewsWithURLString:self.listURLs[self.index] success:^(NSMutableArray *shoppings) {
                    [self setupUrlArray];
            [self.shoppings addObjectsFromArray: shoppings];
            
            [self.collectionView reloadData];
            
            if (![idString isEqualToString:@"all"]) {
                self.index=0;
            }else{
                self.index ++;
            }
        } faild:^(NSError *error) {
            
        }];
        return ;
    }];
    

    [XBShopping loadNewsWithURLString:self.listURLs[self.index] success:^(NSArray *shoppings) {
        
        [self.shoppings addObjectsFromArray:shoppings];
        
        [self.collectionView reloadData];
        self.index ++;
        
    } faild:^(NSError *error) {
        
    }];
}

- (void)layoutCollectionView{
    //注册xib
    UINib *nib = [UINib nibWithNibName:@"XBShoppingCell" bundle:nil];
    [self.collectionView registerNib:nib forCellWithReuseIdentifier:reuseIdentifier];
    //设置collectionVeiw的背景
    self.collectionView.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
    self.collectionView.contentInset = UIEdgeInsetsMake(40, 0, 136, 0);
    
    //从xib中获得cell
    XBShoppingCell *cell = [[nib instantiateWithOwner:self options:nil] lastObject];
    //获取该屏幕宽度
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    //获得宽高比例
    CGFloat present = cell.bounds.size.height/cell.bounds.size.width;
    //为了适配不同屏幕，动态计算宽高
    CGFloat width = (screenWidth - (cnt+1)*10) *0.5;
    CGFloat height =  width * present;
    //    NSLog(@"%f,%f",width,height);
    self.layout.itemSize = CGSizeMake(width,height);
    
    //设置布局
    CGFloat pagging = ([UIScreen mainScreen].bounds.size.width - width *cnt) / (cnt+1);
    
    if ([UIScreen mainScreen].bounds.size.width==414) {
        self.layout.sectionInset = UIEdgeInsetsMake(15, pagging, 0, pagging);
    }else{
        self.layout.sectionInset = UIEdgeInsetsMake(15, 14, 0, 14);
    }
}
- (void)setupTigLabel{
    
    for (int i = 0; i < 4; ++i) {
        CGFloat tigLabelX = (60+20) *i +20;
        UILabel *tigLabel = [[UILabel alloc] initWithFrame:CGRectMake(tigLabelX, 20, 50, 30)];
        tigLabel.backgroundColor = [UIColor grayColor];
        tigLabel.text = @"全部";
        tigLabel.textAlignment = NSTextAlignmentCenter;
        tigLabel.textColor = [UIColor whiteColor];
        tigLabel.font = [UIFont systemFontOfSize:14];
        [self.addView addSubview:tigLabel];
    }
}
#pragma mark  - UICollectionView数据源方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.shoppings.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    XBShopping *shopping = self.shoppings[indexPath.item];
    XBList *list = [shopping.imgs lastObject];

    XBShoppingCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    cell.shopping = shopping;
    cell.list = list;
    
    return cell;
}

#pragma mark - 懒加载
- (NSMutableArray *)shoppings{
    if (_shoppings ==  nil) {
        _shoppings = [NSMutableArray array];
    }
    return _shoppings;
    
}
- (NSMutableArray *)listURLs{
    if (_listURLs==nil) {
        _listURLs = [NSMutableArray array];
    }
    return _listURLs;
}
-(UIButton *)updownbtn{
    if (_updownbtn==nil) {
        _updownbtn = [[UIButton alloc] initWithFrame:CGRectMake(350, 0, 44, 44)];
        _updownbtn.backgroundColor = [UIColor redColor];
        [_updownbtn setImage:[UIImage imageNamed:@"icon_menu_down"] forState:UIControlStateNormal];
        [_updownbtn setImage:[UIImage imageNamed:@"icon_menu_up"] forState:UIControlStateSelected];
    }
    return _updownbtn;
}

@end
